import api from '@/pages/measurements/api'
import { getData, postData, putData } from '@/servers/http'
import { useEffect, useState } from 'react'
import { history } from 'umi'
export default function (id, preview) {
    // 题数
    const [questionCount, setQuestionCount] = useState(0)
    // 问题列表
    const [questionList, setQuestionList] = useState([])
    // 回答列表
    const [answerList, setAnswerList] = useState([])
    // 当前题对应答案
    const [currentAnwser, setCurrentAnwser] = useState([])
    // 当前问题
    const [currentQuestion, setCurrentQuestion] = useState({})
    // 当前问题索引
    const [currentQuesIndex, setCurrentQuesIndex] = useState(0)
    // 当前题是否为段落说明
    const [isDesc, setIsDesc] = useState(false)
    // 当前答题进度
    const [percent, setPercent] = useState(0)
    // 当前题号
    const [currentNo, setCurrentNo] = useState('0')
    // 是否有跳题逻辑
    const [isSkipQuestion, setIsSkipQuestion] = useState(false)
    // 是否为运营人员预览
    const [isPreview, setIsPreview] = useState(false)
    // 退出Flag
    const [exitFlag, setExitFlag] = useState(false)
    // 切题延迟器
    let timer = null
    // setTimer
    const setTimer = (event, timer, delay = 250) => {
        let newTimer = timer
        newTimer && clearTimeout(timer)
        newTimer = setTimeout(event, delay)
    }

    useEffect(() => {
        getExamDetail(id)
        setIsPreview(Number(preview || 0) === 1)
    }, [])

    // 获取当前题目内容及答案
    useEffect(() => {
        setCurrentQuestion(questionList[currentQuesIndex])
        //getCurrentAnwser(currentQuesIndex)
        setIsDesc(questionList[currentQuesIndex]?.mode === '-1')
        setCurrentNo(currentQuesIndex - getDescCountToNow(currentQuesIndex) + 1)

        document.querySelector('#container_top').scrollIntoView()
    }, [currentQuesIndex])

    // 计算当前答题进度
    useEffect(() => {
        if (isSkipQuestion) {
            setPercent((questionCount ? (currentQuesIndex - getDescCountToNow(currentQuesIndex)) / questionCount : 0) * 100)
        } else {
            setPercent((questionCount ? answerList.length / questionCount : 0) * 100)
        }
    }, [questionCount, currentQuesIndex, answerList])

    // 获取题目信息
    const getExamDetail = async id => {
        const res = (await getData(`${api.testEvals}${id}`)) || {}
        const { status, data } = res
        if (status !== 200) return
        const { question_count, questions, is_jump } = data || {}
        console.log('question:', questions, question_count)
        setQuestionCount(question_count)
        setQuestionList(questions)
        setCurrentQuestion(questions[currentQuesIndex])
        setIsDesc(Boolean(questions[currentQuesIndex]?.mode === '-1')) // -1=段落说明、0=评分单选试题、1=普通单选试题
        setIsSkipQuestion(Number(is_jump || 0) === 1)
    }

    /**
     * 选择答案
     * @param {*} id 题目ID
     * @param {*} optionId 答案ID
     * @param {*} jumpId 跳转目标题ID：0-默认下一题、-1为答题结束、id为跳转目标题ID
     */
    const checkAnwser = (id, optionId, jumpId) => {
        let answer = { id: id, option_id: optionId }
        let tmpAnwserList = [...answerList]

        if (jumpId === '-1') {
            // 保存跳转题最后一题答案
            tmpAnwserList = [...tmpAnwserList, answer]
        } else if (questionCount === answerList.length) {
            // 更新顺序题最后一题答案
            tmpAnwserList[tmpAnwserList.length - 1] = answer
        } else if (answerList[answerList.length - 1]?.id === questionList[currentQuesIndex]?.id) {
            // 更新当前题目答案
            tmpAnwserList[tmpAnwserList.length - 1] = answer
        } else {
            // 保存当前题目答案
            tmpAnwserList = [...tmpAnwserList, answer]
        }
        setAnswerList(tmpAnwserList)

        if (jumpId === '-1' || (isSkipQuestion && currentQuesIndex === questionList.length - 1)) {
            // 跳题结束，或跳题的最后一题，提交答案
            submitExam(tmpAnwserList)
            return
        }

        if (jumpId !== '0') {
            // 跳到指定题目
            skipToTargetQuestion(jumpId)
            return
        }

        if (questionCount === tmpAnwserList.length) {
            // 最后一题
            return
        }

        nextQuestion()
    }

    /**
     * TODO
     * 获取题目索引对应的答案
     * @param {*} quesIndex 问题索引
     * @returns
     */
    const getCurrentAnwser = quesIndex => {
        for (let i = answerList.length; i > 0; i--) {
            if (questionList[quesIndex].id === answerList[i]?.id) {
                setCurrentAnwser(answerList[i])
                return
            }
        }
    }

    // 回到上一题
    const backToPrevQuestion = () => {
        setTimer(() => {
            let prevIndex = currentQuesIndex - 1

            if (questionList[prevIndex]?.mode === '-1') {
                // 如果上一题是段落说明继续向前
                prevIndex > 0 && prevIndex--
            }

            if (isSkipQuestion) {
                // 获取上一道回答题目的索引
                prevIndex = getPrevQuestionIndex(false)
            }
            if (isSkipQuestion && prevIndex === currentQuesIndex) {
                // 上一道已回答题目为当前题目时，取前一道已回答题目的索引
                prevIndex = getPrevQuestionIndex(true)
            }

            // 回到上一题
            setCurrentQuesIndex(prevIndex)

            // 更新答案
            const prevId = questionList[prevIndex].id
            setAnswerListToPrev(prevId)
        }, timer)
    }

    // 选择答案后自动下一题
    const nextQuestion = () => {
        setTimer(() => {
            currentQuesIndex < questionList.length - 1 && setCurrentQuesIndex(currentQuesIndex + 1)
        }, timer)
    }

    /**
     * TODO
     * 手动跳转到下一题
     * @returns
     */
    const handleNextQuestion = () => {
        // 当前题目ID
        let currentQuesId = questionList[currentQuesIndex]?.id

        // 当前题是否已回答
        let isAnwser = answerList[answerList.length - 1]?.id === questionList[currentQuesIndex].id
        if (isAnwser) {
            let jumpId = questionList.find(ele => ele.id === currentQuesId).options.find(ele => ele.id === answerList.find(ele => ele.id === currentQuesId).option_id).jump_question_id

            if (jumpId !== '0') {
                // 跳到指定题目
                skipToTargetQuestion(jumpId)
            } else {
                nextQuestion()
            }
        }
    }

    /**
     * TODO
     * 根据答案和当前题目ID,查找已回答的下一题ID
     * @param {*} currentQuesId 当前题ID
     * @returns -1:没有已回答的下一题
     */
    const getNextQuesId = currentQuesId => {
        console.log(currentQuesId, answerList)
        for (let i = answerList.length - 1; i >= 0; i--) {
            console.log(answerList[i].id)
            if (answerList[i].id === currentQuesId) {
                if (i + 1 >= answerList.length) return -1
                // 下一道已回答题目ID
                return answerList[i + 1].id
            }
        }
        return -1
    }

    /**
     * 根据题目ID获取题目对应的索引
     * @param {*} quesId
     */
    const getIndexByQuesId = quesId => {
        for (let i = 0; i < questionList.length; i++) {
            if (quesId === questionList[i].id) {
                return i
            }
        }
        return -1
    }

    // 跳到指定题
    const skipToTargetQuestion = id => {
        setTimer(() => {
            for (let i = currentQuesIndex; i < questionList.length; i++) {
                if (id === questionList[i].id) {
                    setCurrentQuesIndex(i)
                    break
                }
            }
        }, timer)
    }

    // 点击段落说明我知道了
    const iKnow = () => {
        setCurrentQuesIndex(currentQuesIndex + 1)
    }

    // 提交测评
    const submitExam = async answerList => {
        // console.log(answerList)
        if (answerList?.length === 0) {
            return
        }

        let params = {
            questions: answerList,
        }

        // 运营预览
        if (isPreview) {
            params = { ...params, is_monitor: 1 }
        }
        console.log(params)

        // getData(`${api.userBarriersIsFinish}${id}`).then(async res => {
        // if (res?.status === 200) {
        // if (res?.data?.is_finish !== '0') {
        //     const { status, data } =
        //         (await putData(`${api.userBarriersBatchUpdate}${id}`, params)) || {}
        //     if (status !== 200) return
        //     data && localStorage.setItem('measurement_result', JSON.stringify(data))
        //     history.replace(`/measurements/result?eval_id=${id}`)
        // } else {
        const { status, data } = (await postData(`${api.testEvalsSave}`, { ...params, eval_id: id })) || {}
        if (status !== 200) return
        data && localStorage.setItem('measurement_result', JSON.stringify(data))
        history.replace(`/job/ability`)
        // }
        // }
        // })
    }

    /**
     * 根据答案，获取跳题情况下的上一题索引
     * @param {*} isAnwsered 当前题目是否已回答
     * @returns
     */
    const getPrevQuestionIndex = isAnwsered => {
        let quesId = 0
        if (isAnwsered) {
            // 当前题目已回答时取前一道已回答题目的索引
            quesId = answerList[answerList.length - 2]?.id || 0
        } else {
            // 当前题目未回答时取上一道已回答题目的索引
            quesId = answerList[answerList.length - 1]?.id
        }

        if (quesId === 0) {
            return 0
        }

        for (let i = 0; i < questionList.length; i++) {
            if (quesId === questionList[i].id) {
                return i
            }
        }
    }

    // 将答案回退到上一题时的数据
    const setAnswerListToPrev = prevId => {
        let tmpAnwserList = [...answerList]
        let prevIndex = 0
        for (let i = tmpAnwserList.length - 1; i > 0; i--) {
            if (tmpAnwserList[i].id === prevId) {
                prevIndex = i
                break
            }
        }
        let newAnwserList = tmpAnwserList.splice(0, prevIndex + 1)
        setAnswerList(newAnwserList)
    }

    // 获取答题到现在总共有几个段落
    const getDescCountToNow = index => {
        let count = 0
        for (let i = 0; i < index; i++) {
            if (questionList[i].mode === '-1') {
                count++
            }
        }
        return count
    }

    return {
        currentNo,
        questionCount,
        questionList,
        answerList,
        currentAnwser,
        currentQuestion,
        currentQuesIndex,
        backToPrevQuestion,
        handleNextQuestion,
        checkAnwser,
        submitExam,
        isSkipQuestion,
        isDesc,
        iKnow,
        percent,
        exitFlag,
        setExitFlag,
    }
}
